define(function(require, exports){
	var $       = require("jquery");
	var util    = require('util');
	var pubjs   = require('pubjs');
	var view    = require('@base/view');
	var utilDSP = require('modules/common');

	var TYPE = {
		// pc类型
		PC: 1,
		// 移动类型
		MOBILE: 4
	};

	var Campaign = view.container.extend({
		init:function(config){
			config = pubjs.conf(config, {
				'class': 'P-campaignList',
				'addHref': 'campaign/edit',	// 新建路径
				'addHrefBrand': 'serving/campaignEdit',	// 品牌版新建路径
				'vModel':{
					'view': {
						addButton: pubjs.checkRight('campaign.add')
					},
					'vmClickAdd': this.eventClickAdd
				}
			});
			this.$param = {
				'type': 0,	//广告类型.
				'channel': [
					{id: 0}		//pc渠道.
					,{id: 0}	//监测渠道.
					,{id: 0}	////移动渠道.
				]
			};
			this.Super('init', arguments);
            this.$subChannelCache = {};
		},
		afterBuild:function(){
			var self = this;
			var c = self.getConfig();

			self.append($([
				'<div class="M-formHead">',
					'<button v-show="view.addButton" class="btn btn-primary" v-on:click="vmClickAdd">'+LANG('新建推广组')+'</button>',
					'<span class="fr" pub-name="date" pub-mod="@base/common/date.dateRangeNew"/>',
				'</div>',
				'<div class="cl" pub-name="highGrid" pub-mod="campaign/grid/campaign.base"/>'
			].join('')));

			var sidebar_options = [
				// {'name': 'type', 'uri':'modules/sideBarBase.campaignType', type: 'campaign'}
			];

			if(pubjs.checkRight('plan.list'))
			{
				sidebar_options.push({'name': 'plan', 'uri':'modules/sideBarBase.plan'});
			}

			[].push.apply(sidebar_options, [
				{'name': 'channel', 'uri':'modules/sideBarBase.channel','config':{'filterAccess': true,'monitorUrl':""}},
				{'name': 'plan', 'uri': 'modules/sideBarBase.qualificationRadio', 'config': {
					'title': LANG('计划：'),
					'data': [
						{id: 0, name: LANG('全部')},
						{id: 1, name: LANG('指定计划')}
					],
					'value': 0,
					'select_config': {
						url: 'plan/list',
						name: LANG('添加筛选计划'),
						grid_mod: 'campaign/modules/select.nameGrid',
						param: {
							// 'no_limit': true,
							'mongoField': ['_id', 'Name']
						},
						gridTitle: LANG('选择计划')
					}
				}},
				{'name': 'status', 'uri':'modules/sideBarBase.radio', 'config': {
					'title': LANG('状态：'),
					'data': [
						{id: 0, name: LANG('所有有效活动')},
						{id: 2, name: LANG('进行中')},
						{id: 4, name: LANG('已暂停')},
						// {id: 3, name: LANG('已结束')},
						// {id: 1, name: LANG('未开始')},
						{id: 5, name: LANG('超预算')},
						{id: 6, name: LANG('草稿')},
						{id: 7, name: LANG('已归档')}
					],
					'value': 0
				}},
				{'name': 'label', 'uri':'modules/sideBarBase.label', 'config': {
					url: 'campaign/labels'
				}},
				{'name': 'metrics', 'uri':'modules/sideBarBase.metrics', 'config': {
					'metrics': ["{front}","{back}","{conversion}","{cost}"]
				}}
			]);

			var config = {
				'chart':{
				},
				'highGrid': {
					hasMenu: true,
					hasCompare: pubjs.checkRight('compareDim.list'),
					// hasCompare: true,
					hasBatch: true,
					hasSelect: true,
					hasAmount: true,
					hasAutoRefresh: true,
					eventDataLoad: true, // 加载完数据后发消息
					hasExport: pubjs.checkRight('campaign.export'),
					hasRefresh: true,
					hasTab: true,
					hasSearch: true,
					hasFilter: true,
					subs: [
						'mediaAndAd','mediaAndAd_Monitor',
						'sweety','whisky',
						'period','frequency','region',
						'client','product', 'channelCategory',
						'people'
					],
					param: {
						AdvertiserId: +util.getQueryString('aderId'),
						PlanId: +util.getQueryString('planId')
					},
					hasFilterSidebar: true,
					// filterAutoFire: true, //导致重新请求报错，这个目的是什么
					sidebar_config: {
						'items': sidebar_options
					},
					compareOptions: [
						{id: 'compare_period', name: LANG('时段分析')},
						{id: 'compare_spot', name: LANG('广告位')},
						{id: 'compare_whisky', name: LANG('落地页')},
						{id: 'compare_sweety', name: LANG('创意包')}

					]
				},
				'date': {
					'pos': 'bR'
				}
			};

			if(pubjs.checkRight('campaign.oneKeyDiagnose'))
			{
				config.highGrid.header_modules = [
					{
						'name': 'diagnose', // 模块名称
						'html': '<div class="fl M-HighGridExport"><i class="icon-diagnose"/></div>'
					}
				]
			}

			self.vm.mount();


			self.buildFromTemplate(config);
			// 批量编辑界面窗口
			self.createAsync('batchEdit', 'campaign/popwin/batchEdit.main');
		},
		afterBuildTemplate: function(mod, param){
			// var date = this.$.date;
			//var chart = this.$.chart;
			// 更新趋势图的标题
			//chart.changeTitle(date.getData());
		},
		eventClickAdd: function(ev){
			var c = this.getConfig();
			pubjs.controller.navigate(c.addHrefBrand + utilDSP.getBrandSearch());
		},
		onGridHeaderCustom: function(ev){
			if(ev && ev.param && ev.param.name == 'diagnose')
			{
				var selectIds = this.$.highGrid.getSelectRowIds();
				if(!selectIds || !selectIds.length)
				{
					return pubjs.alert(LANG('请先选择一个广告投放活动'));
				}
				else if(selectIds.length > 1)
				{
					return pubjs.alert(LANG('一次只能诊断一个活动'));
				}

				window.open('#campaign/oneKeyDiagnosis/' + selectIds[0]);
				this.$.highGrid.setSelectRowIds([]);
				this.reload();
			}
		},
		// 批量操作-下拉菜单界面
		onBatchShow: function(ev){
			// TODO: 根据权限展示弹出菜单
			// TODO: 根据选中内容展示弹出菜单
			var list = [];
			if (pubjs.checkRight('campaign.update'))
			{
				list = [
					{
						id: 'set',
						name: LANG('设置'),
						subs: [
							{id: 'batchEdit.price', name: LANG("修改出价")},
							{id: 'batchEdit.budget', name: LANG("修改预算")},
							{id: 'batchEdit.bidSpeed', name: LANG("投放速度")},
							{id: 'batchEdit.frequency', name: LANG("频次控制")},
							{id: 'batchEdit.date', name: LANG("投放日期")},
							{id: 'batchEdit.timeset', name: LANG("日程设置")},
							{id: 'batchEdit.zone', name: LANG("投放地区")},
							{id: 'batchEdit.client', name: LANG("客户端")},
							{id: 'batchEdit.smartMonitor', name: LANG("智能监控")},
							{id: 'batchEdit.nameReplace', name: LANG('活动名称关键词替换')}
						]
					}
				];

				if(pubjs.checkRight('campaign.amonitor'))
				{
					list[0].subs.push({id: 'batchEdit.aMonitorUrl', name: LANG('三方监测地址')});
				}
			}

			var batch = [
				{id: 'pause', name: LANG('暂停')},
				{id: 'start', name: LANG('开始')},
				{id: 'delete', name: LANG('归档'), right: 'remove'},
				{id: 'recover', name: LANG('还原')},
				{id: 'export', name: LANG('导出')}
			];

			// 检查权限
			util.each(batch, function(item){
				if (pubjs.checkRight('campaign.' + (item.right || item.id)))
				{
					list.push(item);
				}
			});
			ev.returnValue = list;
			return false;
		},
		// 批量操作-响应菜单操作
		onBatchSelect: function(ev){
			var data = ev.param[0];
			var ids = ev.param[1];
			var contents = ev.param[2];
			var key = data.key || '';
			var channelType = 0;	// 活动类型

			if(!ids || !ids.length) {
				pubjs.alert(LANG('请先选择活动'));
				return false;
			}

			// 设置子菜单的部分内容编辑,id是用点分割
			var keys = key.split('.');
			if(keys[1] === 'character' || keys[1] === 'client'){
				var _tmp = {};
				for(var i=0; i<contents.length; i++){
					if(contents[i]){
						var type = contents[i].Channel;
						_tmp[type] = true;
						// 修改人群选择和客户端，同时勾选PC和移动的，弹窗弹窗提示
						if(_tmp[TYPE.PC] && _tmp[TYPE.MOBILE]) {
							pubjs.alert(LANG('不能同时选择PC和移动'));
							return false;
						}else{
							// 记录活动类型
							channelType = type;
						}
					}
				}
			}

			// 判断是否PC端的，如果是PC端的弹出弹窗提示
			if(keys[1] === 'terminalType'){
				for(var j=0; j<contents.length; j++){
					var type2 = contents[j].Channel;
					if(type2 === TYPE.MOBILE){
						pubjs.alert(LANG('只有PC的才可以修改终端类型'));
						return false;
					}
				}
			}

			if (keys.shift() === 'batchEdit') {
				this.$.batchEdit.reset().show().setTitle(data.name).setChannelType(channelType).setType(keys.shift()).setParam(ids);
				return false;
			}

			var self = this;
			switch(key){
				case 'start':
					self.send('campaign/start',{'id': ids }, 'onBatchEditSuccess');
				break;
				case 'pause':
					self.send('campaign/pause',{'id': ids }, 'onBatchEditSuccess');
				break;
				case 'delete':
					pubjs.confirm(LANG('确认删除以下推广组 %1 吗', ids), function(state) {
						if(state)
						{
							self.send('campaign/remove',{'id': ids }, 'onBatchEditSuccess');
						}
					});
				break;
				case 'recover':
					self.send('campaign/recover',{'id': ids }, 'onBatchEditSuccess');
				break;
				case 'export':
					var url = utilDSP.getExportApi(this.get('highGrid'), ids);
					window.location.href = url;
				break;
			}
			return false;
		},
		send: function(url, param, cbName)
		{
			if(url)
			{
				pubjs.loading.show();
				var self = this;
				pubjs.mc.send(url, param, function(err) {
					pubjs.loading.hide();
					if(err)
					{
						return pubjs.alert(err.message);
					}

					pubjs.alert(LANG('操作成功'));
					self[cbName || 'reload'].apply(self, arguments);
				});
			}
		},
		// 操作菜单-下拉菜单界面
		onOperateMenuShow: function(ev){
			/**
				Status：
				1 正常/进行中
				2 暂停
				3 草稿
				4 未开始
				5 已结束
				6 超预算
			**/

			var param = ev.param;
			var result = [];
			if(!param.IsDeleted)
			{
				if(!param.IsDraft)
				{
					if (param.Status === 1 && pubjs.checkRight('campaign.pause'))
					{
						//检查是否有暂停活动的权限
						result.push({id: 'pause', name: LANG('暂停')});
					}
					else if (pubjs.checkRight('campaign.start'))
					{
						//检查是否有开启活动的权限
						result.push({id: 'start', name: LANG('开启')});
					}

					// 绘图功能
					// var menu = ev.from.getDOM();
					/*
					if(menu.hasClass('drawing')){
						result.push({id: 'unDraw', name: LANG('取消绘图')});
					}else{
						result.push({id: 'draw', name: LANG('绘图')});
					}
					*/


					//检查是否有编辑权限
					if (pubjs.checkRight('campaign.update'))
					{
						result.push({id: 'edit', name: LANG('编辑')});
					}
					else if (pubjs.checkRight('campaign.info'))
					{
						result.push({id: 'edit', name: LANG('查看详情')});
					}

					//检查是否有删除权限
					if (pubjs.checkRight('campaign.remove'))
					{
						result.push({id: 'delete', name: LANG('归档')});
					}

					//rtb渠道，同时检查活动诊断的权限
					if((param.Channel === 1 || param.Channel === 4) && pubjs.checkRight('campaign.diagnosis'))
					{
						// 代理没有活动诊断
						result.push({id: 'diagnosis', name: LANG('活动诊断')});
					}
				}
				else
				{
					//检查是否有编辑活动的权限
					if (pubjs.checkRight('campaign.update'))
					{
						result.push({id: 'edit', name: LANG('编辑')});
					}
				}
			}
			else
			{
				if (pubjs.checkRight('campaign.recover'))
				{
					// 已归档的只有'还原'操作
					result.push( {id: 'recover', name: LANG('还原')} );
				}
			}

			//如果没有新建的权限，应该就不给另存为了吧。
			if (pubjs.checkRight('campaign.add'))
			{
				result.push( {id: 'saveas', name: LANG('另存为')} );
			}

			//广告监测的广告位代码
			if(param.Channel === 2)
			{
				result.push( {id: 'code', name: LANG('广告位代码')} );
			}

			ev.returnValue = result;
			return false;
		},
		// 操作菜单-响应菜单操作
		onOperateMenuSelect: function(ev){
			var op = ev.param[0];
			var data = ev.param[1];
			var c = this.getConfig();
			var menu = ev.from.getDOM();
			var id = +data._id;
			var self = this;

			switch(op.key){
				case 'start':
					self.send('campaign/start', {'id': id });
				break;
				case 'pause':
					self.send('campaign/pause', {'id': id });
				break;
				case 'delete':
					pubjs.confirm(LANG('确认删除推广组ID: %1 ,名称："%2"吗', id, data.Name), function(state) {
						if(state)
						{
							self.send('campaign/remove',{'id': id});
						}
					});
				break;
				case 'recover':
					self.send('campaign/recover', {'id': id });
				break;
				case 'edit':
					if(c.isBrand){
						pubjs.controller.navigate('serving/campaignEdit/' + id + utilDSP.getBrandSearch());
					}else{
						var type = data['Channel'] || '1';
						var typeMap = {
							'1': 'edit',
							'2': 'agentEdit',
							'4': 'MTEdit'
						};
						var uri = '#campaign/' + typeMap[type] + '/';
						//pubjs.controller.navigate(uri + id );
						window.open(uri + id);
					}

				break;
				case 'download':
					pubjs.controller.navigate(c.urlDownload + id );
				break;
				case 'diagnosis':
					//pubjs.controller.navigate('campaign/diagnosis/' + id);
					window.open('#campaign/diagnosis/' + id);
				break;
				case 'draw':
					menu.toggleClass('drawing');
					//this.$.chart.toggleChart(true).toggleDraw(id);
				break;
				case 'unDraw':
					menu.toggleClass('drawing');
					//this.$.chart.toggleChart(false);
				break;
				case 'saveas':
					//pubjs.controller.navigate('campaign/saveas/' + id+'?type='+data.Channel);
					window.open('#campaign/saveas/' + id);
				break;
				case 'code':
					//pubjs.controller.navigate('campaign/code/' + id);
					window.open('#campaign/code/' + id);
				break;
			}
			return false;
		},
		// 时间控件
		onDateRangeChange: function(ev) {
			//TODO:图表重绘
			if(this.$.chart){
				this.$.chart.changeTitle(this.$.date.getData());
				// 如果趋势图是打开状态，才加载趋势图数据
				if(!this.$.chart.$collapse){
					// 更新时间参数
					var date = pubjs.getDate();
					this.$.chart.load(date);
				}
			}
		},
		reload: function(){
			this.$.highGrid.reload({
				AdvertiserId: +util.getQueryString('aderId'),
				PlanId: +util.getQueryString('planId')
			});
		},
		// 批量编辑 -- 设置中模块编辑完成
		onBatchEditSuccess: function(ev) {
			var ids = this.$.highGrid.getSelectRowIds();
			this.$.highGrid.setSelectRowIds([]);
			this.reload();
			// 本页grid
			pubjs.core.cast('savePlanSuccess', {ids: ids});
			// 其他tab的grid
			if (utilDSP.checkOpener() && window.opener && window.opener.pubjs)
			{
				window.opener.pubjs.core.cast('saveCampaignSuccess', {ids: ids});
			}
			return false;
		},
		onSidebarFilter: function(ev){
			var self = this
				,param = {};
			util.each(ev.param, function(item, idx){
				var type = idx;
				var id = item.id;
				switch (type) {
					case 'type':
						self.$type = +id; // 缓存请求的活动类型
						param.Channel = +id;
						break;
					case 'channel':
						param.SubChannel = +id;
						break;
					case 'label':
						param.Labels = id;
						break;
					case 'status':
						param.Status = +id;
						break;
					case 'metrics':
						param.metrics_filter = id;
						break;
					case 'plan':
						param.PlanId = item.data;
						break;
				}
			});
			self.$.highGrid.reload(param);
		},
		onSidebarFilterGroup: function(ev)
		{
			if (ev.name == 'plan')
			{
				if(ev.param.data.length){
					this.$.highGrid.reload({PlanId: ev.param.data});
				}
				this.cast('sidebarFilterResult', {'plan': ev.param});
			}
		},
		// 避免计划筛选完成，筛选拦隐藏的问题
		onMainPopwinOk: function(){
			this.$.highGrid.showPanel();
			return false;
		},
		// 表格数据加载完之后
		onGridDataLoad: function() {
			var grid = this.$.highGrid;
			// 广告监测表格没有出价一列
			// @todo 优化，要隐藏整个竞价组

			var TopPriceMetric = util.find(grid.$sysParam.metrics,'TopPrice');
			if(TopPriceMetric){
				if( this.$type == '2' ) {
					grid.toggleColumn('TopPrice', false, 'sub');
				}
				else {
					grid.toggleColumn('TopPrice', true, 'sub');
				}
			}
			return false;
		},
		onSearch: function(ev){
			this.$.highGrid.reload({"word": ev.param});
			return false;
		},
		onChartToggle: function(ev){
			this.$.highGrid.calculate(true);
			this.$.highGrid.updateScroller();
			return false;
		},
		onUpdateBudget: function(ev){
			this.reload();
			return false;
		},
		/**
		 * 活动表格成功保存事件
		 */
		onSaveCampaignSuccess: function(ev)
		{
			this.reload();

			if (ev.param && ev.param.id)
			{
				this.$.highGrid.setRowHighlight(ev.param.id);
			}

			if (ev.param && ev.param.ids && ev.param.ids.length)
			{
				var ids = ev.param.ids;
				for (var i = 0; i < ids.length; i++)
				{
					this.$.highGrid.setRowHighlight(+ids[i]);
				}
			}
		}
	});
	exports.main = Campaign;
});